import { history as router } from 'umi';
import { message } from 'antd';
import {
  fakeAccountLogin,
  getFakeCaptcha,
  getMenuData,
  initCaptcha,
  drawCaptcha,
} from '@/services/login';

const Model = {
  namespace: 'userLogin',
  state: {
    isLogin: false,
    currentUser: {},
    menuData: [],
    permissions: [],
    logerr: '',
    captchaImg: '',
    captchaId: '',
    deptList: [],
  },
  effects: {
    *login({ payload, callback }, { call, put, select }) {
      try {
        const response = yield call(fakeAccountLogin, payload);
        if (response.success) {
          yield put({
            type: 'changeLoginStatus',
            payload: response,
          });
          if (callback) callback(response.data);
        } else {
          const errorMessage = response.errorMsg;
          message.warning(errorMessage);
        }
      } catch (e) {
        const logerr = yield select(({ userLogin }) => userLogin.logerr);
        message.error(logerr, 2);
        yield put({
          type: 'setLoginError',
          payload: '',
        });
      }
    },
    *getMenuData({ payload }, { call, put }) {
      const response = yield call(getMenuData, payload);
      if (response.success) {
        const { children } =
          (response.data instanceof Array && response.data.length !== 0 && response.data[0]) || [];
        const { path, children: child = [] } =
          (children instanceof Array && children.length !== 0 && children[0]) || {};
        yield put({
          type: 'handleMenuData',
          payload: response,
        });
        if (child?.length) {
          router.push(child[0].path);
        } else {
          router.push(path);
        }
      }
    },
    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
    *getCaptchaImg(_, { call, put }) {
      const res = yield call(initCaptcha);
      const imgData = yield call(drawCaptcha, res.data);
      yield put({
        type: 'saveCaptchaId',
        payload: res.data,
      });
      yield put({
        type: 'saveCaptchaImg',
        payload: window.URL.createObjectURL(imgData),
      });
    },
    *checkLogin(state, { put }) {
      const loginfo = yield JSON.parse(localStorage.getItem('loginfo'));
      if (loginfo) {
        yield put({ type: 'replaceState', payload: loginfo });
      } else {
        yield router.replace(`/userLogin?redirect=${window.location.href}`);
      }
    },
    *logout(state, { put }) {
      localStorage.clear();
      yield put({
        type: 'replaceState',
        payload: {
          isLogin: false,
          currentUser: {},
          menuData: [],
        },
      });
      yield router.replace(`/userLogin?redirect=${window.location.href}`);
    },
  },
  reducers: {
    setLoginError(state, { payload }) {
      return { ...state, logerr: payload };
    },
    changeLoginStatus(state, { payload }) {
      const isLogin = payload.success;
      const {
        data: { permissions },
      } = payload;
      const loginfo = {
        ...state,
        isLogin,
        type: payload.type,
        currentUser: payload.data.user,
        userToken: payload.data.token,
        permissions,
      };
      localStorage.setItem('loginfo', JSON.stringify(loginfo));
      return loginfo;
    },
    handleMenuData(state, { payload }) {
      const menuData = payload.data[0].children;
      const newstate = { ...state, menuData };
      localStorage.setItem('loginfo', JSON.stringify(newstate));
      return newstate;
    },
    replaceState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    saveCaptchaId(state, { payload }) {
      return {
        ...state,
        captchaId: payload,
      };
    },
    saveCaptchaImg(state, { payload }) {
      return {
        ...state,
        captchaImg: payload,
      };
    },
    setKeyValue(state, { payload }) {
      return {
        ...state,
        [payload.key]: payload.val,
      };
    },
  },
};
export default Model;
